package com.ggb.smartstudy.controller;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;


import java.util.HashMap;
import java.util.Map;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public Map<String, Object> handleError(HttpServletRequest request, WebRequest webRequest) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        Map<String, Object> errorAttributes = new HashMap<>();
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            errorAttributes.put("status", statusCode);
            errorAttributes.put("error", HttpStatus.valueOf(statusCode).getReasonPhrase());
            Object message = webRequest.getAttribute(RequestDispatcher.ERROR_MESSAGE, WebRequest.SCOPE_REQUEST);
            if (message != null) {
                errorAttributes.put("message", message.toString());
            } else {
                errorAttributes.put("message", "An unexpected error occurred.");
            }
        } else {
            errorAttributes.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorAttributes.put("error", "Internal Server Error");
            errorAttributes.put("message", "An unexpected error occurred.");
        }
        return errorAttributes;
    }
}